import { ethers } from 'ethers';
/**
 * KYC API Test for RWA Platform
 * 使用fetch API直接测试KYC相关端点
 * 
 * 运行方式：
 * 1. 确保应用程序正在运行 (npm run start:dev)
 * 2. 在浏览器控制台或Node.js环境中运行此文件
 */

const BASE_URL = 'http://localhost:3000';
const API_BASE = `${BASE_URL}/api/v1`;

interface TestResult {
    endpoint: string;
    method: string;
    status: number;
    success: boolean;
    data?: any;
    error?: string;
}

class KycAPITester {
    private results: TestResult[] = [];
    private authToken: string | null = null;
    private walletAddress: string | null = null;
    private chainId: number = 1; // Ethereum Mainnet

    async testEndpoint(
        endpoint: string,
        method: string = 'GET',
        body?: any,
        headers: Record<string, string> = {}
    ): Promise<TestResult> {
        const url = `${API_BASE}${endpoint}`;
        const defaultHeaders: Record<string, string> = {
            'Content-Type': 'application/json',
            ...headers,
        };

        if (this.authToken) {
            defaultHeaders['Authorization'] = `Bearer ${this.authToken}`;
        }

        try {
            const response = await fetch(url, {
                method,
                headers: defaultHeaders,
                body: body ? JSON.stringify(body) : undefined,
            });

            let data;
            try {
                data = await response.json();
            } catch {
                data = await response.text();
            }

            const result: TestResult = {
                endpoint,
                method,
                status: response.status,
                success: response.ok,
                data: response.ok ? data : undefined,
                error: response.ok ? undefined : data?.message || response.statusText,
            };

            this.results.push(result);
            return result;
        } catch (error) {
            const result: TestResult = {
                endpoint,
                method,
                status: 0,
                success: false,
                error: error instanceof Error ? error.message : 'Unknown error',
            };
            this.results.push(result);
            return result;
        }
    }

    async runAllTests(): Promise<void> {
        console.log('🔍 Starting KYC API Tests...\n');

        // 首先进行钱包认证
        await this.authenticateWallet();

        // 测试KYC端点
        await this.testKycEndpoints();

        // 输出测试结果摘要
        this.printTestSummary();
    }

    private async authenticateWallet(): Promise<void> {
        console.log('🔐 Authenticating Wallet for KYC Tests...');

        // 使用ethers进行离线签名
        // 注意：此处仅用于测试，私钥请勿用于生产环境
        const testPrivateKey = '9b225c646ba70c3e57756bdc8e30d6ac0fa5b614ed9baae00e92740713894eb2';
        const wallet = new ethers.Wallet(testPrivateKey);

        // 构造待签名消息
        const message = 'Welcome to RWA Platform! Please sign this message to authenticate.';

        // 进行离线签名
        const signature = await wallet.signMessage(message);

        // 输出签名和钱包地址
        console.log('📝 离线签名结果:');
        console.log('钱包地址:', wallet.address);
        console.log('链ID:', this.chainId);
        console.log('签名:', signature);

        // 测试钱包登录
        const authData = {
            walletAddress: wallet.address,
            chainId: this.chainId,
            message: message,
            signature: signature,
            fullName: 'KYC Test User'
        };

        const authResult = await this.testEndpoint('/auth/wallet-login', 'POST', authData);

        if (authResult.success && authResult.data?.access_token) {
            this.authToken = authResult.data.access_token;
            this.walletAddress = authResult.data.user.walletAddress;
            console.log('✅ Authentication successful, token obtained');
        } else {
            console.log('⚠️ Authentication failed:', authResult.error);
            throw new Error('Authentication failed - cannot proceed with KYC tests');
        }

        console.log('');
    }

    private async testKycEndpoints(): Promise<void> {
        console.log('🆔 Testing KYC Endpoints...');

        // 1. 创建 KYC 申请人
        console.log('1. Testing KYC Applicant Creation...');
        const createResult = await this.testEndpoint('/kyc/create', 'POST');
        if (createResult.success) {
            console.log('✅ KYC Applicant created successfully');
            console.log('Applicant ID:', createResult.data?.data?.id);
        } else {
            console.log('❌ KYC Applicant creation failed:', createResult.error);
        }

        // 2. 获取 KYC Token
        console.log('\n2. Testing KYC Token Generation...');
        const tokenResult = await this.testEndpoint('/kyc/token', 'POST');
        if (tokenResult.success) {
            console.log('✅ KYC Token generated successfully');
            console.log('Token:', tokenResult.data?.data?.token?.substring(0, 50) + '...');
        } else {
            console.log('❌ KYC Token generation failed:', tokenResult.error);
        }

        // 3. 获取 KYC 状态
        console.log('\n3. Testing KYC Status Retrieval...');
        const statusResult = await this.testEndpoint('/kyc/status', 'GET');
        if (statusResult.success) {
            console.log('✅ KYC Status retrieved successfully');
            const status = statusResult.data?.data;
            if (status) {
                console.log('Status:', this.parseKycStatus(status));
                console.log('Level:', status.level);
                if (status.reviewResult) {
                    console.log('Review Result:', status.reviewResult);
                }
            }
        } else {
            console.log('❌ KYC Status retrieval failed:', statusResult.error);
        }

        // 4. 获取 KYC 详细信息
        console.log('\n4. Testing KYC Info Retrieval...');
        const infoResult = await this.testEndpoint('/kyc/info', 'GET');
        if (infoResult.success) {
            console.log('✅ KYC Info retrieved successfully');
            const info = infoResult.data?.data;
            if (info) {
                console.log('Applicant ID:', info.id);
                console.log('External User ID:', info.externalUserId);
                console.log('Status:', info.status);
                console.log('Created:', info.createdAt);
            }
        } else {
            console.log('❌ KYC Info retrieval failed:', infoResult.error);
        }

        // 5. 获取 KYC 检查结果
        console.log('\n5. Testing KYC Checks Retrieval...');
        const checksResult = await this.testEndpoint('/kyc/checks', 'GET');
        if (checksResult.success) {
            console.log('✅ KYC Checks retrieved successfully');
            const checks = checksResult.data?.data;
            if (checks && Array.isArray(checks)) {
                console.log(`Found ${checks.length} check(s):`);
                checks.forEach((check, index) => {
                    console.log(`  ${index + 1}. ${check.type}: ${check.result} (${check.answer})`);
                });
            } else {
                console.log('No checks found or checks data is not an array');
            }
        } else {
            console.log('❌ KYC Checks retrieval failed:', checksResult.error);
        }

        console.log('');
    }

    private parseKycStatus(statusData: any): string {
        const status = statusData.status;
        const reviewResult = statusData.reviewResult;

        let statusText = '';
        let statusColor = '';

        switch (status) {
            case 'init':
                statusText = '初始化';
                statusColor = '🟡';
                break;
            case 'pending':
                statusText = '等待审核';
                statusColor = '🟡';
                break;
            case 'prechecked':
                statusText = '预检查';
                statusColor = '🟡';
                break;
            case 'queued':
                statusText = '排队中';
                statusColor = '🟡';
                break;
            case 'completed':
                if (reviewResult === 'GREEN') {
                    statusText = '审核通过';
                    statusColor = '🟢';
                } else if (reviewResult === 'RED') {
                    statusText = '审核拒绝';
                    statusColor = '🔴';
                } else if (reviewResult === 'YELLOW') {
                    statusText = '需要补充材料';
                    statusColor = '🟡';
                } else {
                    statusText = '审核完成';
                    statusColor = '🟢';
                }
                break;
            case 'onHold':
                statusText = '暂停审核';
                statusColor = '🟡';
                break;
            case 'rejected':
                statusText = '已拒绝';
                statusColor = '🔴';
                break;
            default:
                statusText = '未知状态';
                statusColor = '⚪';
        }

        return `${statusColor} ${statusText}`;
    }

    private printTestSummary(): void {
        console.log('📊 KYC Test Results Summary:');
        console.log('============================');

        const totalTests = this.results.length;
        const successfulTests = this.results.filter(r => r.success).length;
        const failedTests = totalTests - successfulTests;

        console.log(`Total Tests: ${totalTests}`);
        console.log(`Successful: ${successfulTests}`);
        console.log(`Failed: ${failedTests}`);
        console.log(`Success Rate: ${((successfulTests / totalTests) * 100).toFixed(1)}%`);

        console.log('\n📋 Detailed Results:');
        this.results.forEach((result, index) => {
            const statusIcon = result.success ? '✅' : '❌';
            const statusText = result.success ? 'SUCCESS' : 'FAILED';
            console.log(`${index + 1}. ${statusIcon} ${result.method} ${result.endpoint} - ${statusText} (${result.status})`);

            if (!result.success && result.error) {
                console.log(`   Error: ${result.error}`);
            }
        });

        console.log('\n🎯 KYC Test completed!');

        // 输出测试建议
        if (failedTests > 0) {
            console.log('\n💡 Suggestions:');
            console.log('- 确保 Sumsub 配置正确 (SUMSUB_APP_TOKEN, SUMSUB_SECRET_KEY)');
            console.log('- 检查网络连接和 Sumsub API 可用性');
            console.log('- 验证 JWT token 是否有效');
            console.log('- 确认用户已在 Sumsub 中创建');
        }
    }
}

// 如果直接运行此文件，执行测试
if (typeof window === 'undefined') {
    // Node.js环境
    const tester = new KycAPITester();
    tester.runAllTests().catch(console.error);
} else {
    // 浏览器环境
    (window as any).KycAPITester = KycAPITester;
    console.log('KycAPITester class available in window.KycAPITester');
    console.log('Run: new KycAPITester().runAllTests() to start testing');
}

export { KycAPITester };
